import { Table, Icon, Row, Col, Button, Spin, Modal } from 'antd';

const confirm = Modal.confirm;
import { WeaTools, WeaInput, WeaSelect, WeaBrowser, WeaDatePicker, WeaCheckbox, WeaError } from 'ecCom';
import './style/index.css';
import equal from 'deep-equal';
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;
import { toJS } from 'mobx';

class WeaCrmTableEdit extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [],
      datas: [],
      selectedRowKeys: [],
      current: 1,
      showGroup: props.showGroup ? props.showGroup : false,
      type: props.type || 'nodiscount',
    };
    this.onEdit = this.onEdit.bind(this);
    this.doCopy = this.doCopy.bind(this);
    this.doDelete = this.doDelete.bind(this);
    this.doAdd = this.doAdd.bind(this);


    this.isNoLinkInput = new Array();
    this.isNoLinkBro = [];
    this.isLinkBro = [];
    this.isLinkInput = new Array();
    this.select = [];
    this.datePicker = [];
    this.checkbox = [];
  }

  componentDidMount() {
    const { datas = [], columns = [] } = this.props;
    columns.length > 0 && this.setState(datas.length > 0 ? { datas: this.addKeytoDatas(datas), columns } : { columns });
  }

  componentWillReceiveProps(nextProps, nextState) {
    const { columns = [], datas = [], selectedRowKeys = [] } = this.state;
    const _columns = nextProps.columns || [];
    const _datas = nextProps.datas || [];
    const _selectedRowKeys = nextProps.selectedRowKeys || [];
    this.setState({ columns: _columns });
    !equal(datas, _datas) && this.setState({ datas: this.addKeytoDatas(_datas) });
    !equal(selectedRowKeys, _selectedRowKeys) && this.setState({ selectedRowKeys: _selectedRowKeys });
  }

  componentWillUnmount() {
    this.setState({
      columns: [],
      datas: [],
      selectedRowKeys: [],
      current: 1,
      showGroup: false,
      type: 'nodiscount',
    });
  }

  addKeytoDatas(datas) {
    const _datas = datas.map((data, i) => {
      const _data = { ...data };
      _data.key = i;
      return _data;
    });
    return _datas;
  }

  render() {
    const { datas, showGroup, columns, selectedRowKeys } = this.state;
    const { title, needAdd, needCopy } = this.props;
    return (
      <div className="wea-crm-table-edit" >
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@i330tv`} className="wea-title">
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@0bit4s`} span="20">
            <div>{title}</div>
          </Col>
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@t6bh0p`} span="4" style={{ textAlign: 'right', paddingRight: 10 }}>
            {needAdd &&
            <span>
              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@udeuu3`} type="primary" title={getLabel(1421, '新增')} size="small" onClick={this.doAdd}><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@ctwx1d`} type="plus" /></Button>
              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@im0mdt`} type="primary" disabled={!`${selectedRowKeys}`} title={getLabel(91, '删除')} size="small" onClick={this.doDelete} ><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@67ues3`} type="minus" /></Button>
            </span>
            }
            {needCopy &&
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@j8mfy1`} type="primary" disabled={!`${selectedRowKeys}`} title={getLabel(77, '复制')} size="small" onClick={this.doCopy} ><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@a4yx1y`} type="copy" /></Button>
            }
            <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@0ltgbq`} type={showGroup ? 'up' : 'down'} onClick={() => this.setState({ showGroup: !showGroup })} />
          </Col>
        </Row>
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@latmpp`} className="wea-content" style={{ display: showGroup ? 'block' : 'none' }}>
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@xfwf4b`} span={24}>
            <Table
              ecId={`${this && this.props && this.props.ecId || ''}_Table@zbse5k`}
              columns={this.getColumns()}
              dataSource={datas}
              pagination={false}
              rowSelection={this.getRowSelection()}
            />
          </Col>
        </Row>

      </div>
    );
  }
  getColumns() {
    const { columns } = this.state;
    let _columns = [].concat(columns);
    _columns = _columns.map((col) => {
      const _col = { ...col };
      _col.render = (text, record, index) => this.getColRender(_col, text, record, index);
      return _col;
    });
    return _columns;
  }
  getColRender(_col, text, record, index) {
    const { com, isLink = false, linkKey = [], linkUrl = '' } = _col;
    const _com = [];
    com.map((c,indexCom) => {
      if (typeof c.props === 'object') {
        _com.push(c);
      } else {
        const { domkey, viewAttr, formItemType, options = [], browserConditionParam = {}, width, value, otherParams = {} } = c;
        const _type = formItemType || 'INPUT'.toUpperCase();
        _com.push(
          <span>
            {_type === 'INPUT' && !isLink &&
            <WeaError
              ecId={`${this && this.props && this.props.ecId || ''}_WeaError@5kkkk9@${indexCom}`}
              tipPosition="top"
              style={{ width: '100%' }}
              ref={(obj) => { this.isLinkInput.push(obj); }
                }
              error={`"${_col.title}"${getLabel(21423, '未填写')}`}
            >

              <WeaInput
                ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@rri2x5@${indexCom}`}
                defaultValue={value || ''}
                value={record[domkey[0]]}
                style={{ width, display: 'inline-block' }}
                onChange={value => this.onEdit(record, index, domkey[0], value)}
                viewAttr={viewAttr}
                {...otherParams}
              />
            </WeaError>
            }
            {_type === 'INPUT' && isLink &&
            <WeaError
              ecId={`${this && this.props && this.props.ecId || ''}_WeaError@0jz447@${indexCom}`}
              tipPosition="top"
              ref={(obj) => {
                  this.isLinkInput.push(obj);
                }}
              style={{ width: '100%' }}
              error={`"${_col.title}"${getLabel(21423, '未填写')}`}
            >
              <WeaInput
                ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@0zjzex@${indexCom}`}
                defaultValue={value || ''}
                value={record[domkey[0]]}
                style={{ width, display: 'inline-block' }}
                onChange={value => this.onInptEdit(record, index, domkey[0], value, '', linkKey)}
                viewAttr={viewAttr}
                {...otherParams}
              />
            </WeaError>
            }
            {_type === 'BROWSER' && !isLink &&
            <WeaError
              ecId={`${this && this.props && this.props.ecId || ''}_WeaError@hzoife@${indexCom}`}
              tipPosition="top"
              ref={(obj) => { this.isNoLinkBro[index] = obj; }}
              style={{ width: '100%' }}
              error={`"${_col.title}"${getLabel(21423, '未填写')}`}
            >
              <WeaBrowser
                ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@kwctx9@${indexCom}`}
                layout={document.body}
                {...browserConditionParam}
                replaceDatas={this.getBrowerDatas(record, domkey[0])}
                style={{ width, display: 'inline-block' }}
                onChange={(ids, names, bDatas) => this.onEdit(record, index, domkey[0], ids, names, bDatas)}
              />
            </WeaError>
            }
            {_type === 'BROWSER' && isLink &&
            <WeaError
              ecId={`${this && this.props && this.props.ecId || ''}_WeaError@92nbt4@${indexCom}`}
              tipPosition="top"
              ref={(obj) => { this.isLinkBro[index] = obj; }}
              style={{ width: '100%' }}
              error={`"${_col.title}"${getLabel(21423, '未填写')}`}
            >
              <WeaBrowser
                ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@4ufo33@${indexCom}`}
                layout={document.body}
                {...browserConditionParam}
                replaceDatas={this.getBrowerDatas(record, domkey[0])}
                style={{ width, display: 'inline-block' }}
                onChange={(ids, names, bDatas) => this.onLinkEdit(record, index, domkey[0], ids, names, bDatas, linkUrl, linkKey)}
              />
            </WeaError>
            }
            {_type === 'DATEPICKER' &&
            <WeaError
              ecId={`${this && this.props && this.props.ecId || ''}_WeaError@5zdz2z@${indexCom}`}
              tipPosition="top"
              ref={(obj) => { this.datePicker[index] = obj; }}
              style={{ width: '100%' }}
              error={`"${_col.title}"${getLabel(21423, '未填写')}`}
            >
              <WeaDatePicker
                ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@f6g41e@${indexCom}`}
                value={record[domkey[0]]}
                style={{ width, display: 'inline-block' }}
                formatPattern={2}
                viewAttr={viewAttr}
                onChange={value => this.onEdit(record, index, domkey[0], value)}
              />
            </WeaError>
            }
            {_type === 'CHECKBOX' &&
            <WeaError
              ecId={`${this && this.props && this.props.ecId || ''}_WeaError@nlrm77@${indexCom}`}
              tipPosition="top"
              ref={(obj) => { this.checkbox[index] = obj; }}
              style={{ width: '100%' }}
              error={`"${_col.title}"${getLabel(21423, '未填写')}`}
            >
              <WeaCheckbox
                ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@1erx5l@${indexCom}`}
                value={record[domkey[0]] != '1'}
                style={{ width, display: 'inline-block' }}
                viewAttr={viewAttr}
                onChange={value => this.onEdit(record, index, domkey[0], value == '0' ? '1' : '0')}
              />
            </WeaError>
            }
            {_type === 'SELECT' && isLink && viewAttr != '1' &&
            <WeaError
              ecId={`${this && this.props && this.props.ecId || ''}_WeaError@9h9fnn@${indexCom}`}
              tipPosition="top"
              ref={(obj) => { this.select[index] = obj; }}
              style={{ width: '100%' }}
              error={`"${_col.title}"${getLabel(21423, '未填写')}`}
            >
              <WeaSelect
                ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@63g7zn@${indexCom}`}
                value={record[domkey[0]]}
                style={{ width, display: 'inline-block' }}
                options={options}
                viewAttr={viewAttr}
                hasBorder
                onChange={value => this.onSelectEdit(record, index, domkey[0], value, '', linkKey)}
              />
            </WeaError>
            }
            {_type === 'SELECT' && isLink && viewAttr == '1' &&
            <div>
              {
                  options.map((c) => {
                    if (c.key == record[domkey[0]]) {
                      return c.showname;
                    }
                  })
                }
            </div>
            }
          </span>,
        );
      }
    });
    return (
      <div>
        {_com}
      </div>
    );
  }
  getBrowerDatas(record, key) {
    const replaceDatas = [];
    if (record[`${key}span`] !== undefined) {
      const keys = record[key].split(',');
      const values = record[`${key}span`].split(',');
      if (keys.length === values.length) {
        keys.map((k, i) => {
          replaceDatas.push({ id: k, name: values[i] });
        });
      } else {
        // console.log('浏览按钮数据有误！！，显示名中不能包含有英文逗号" , "');
      }
    }
    return replaceDatas;
  }
  getRowSelection() {
    const { columns, selectedRowKeys } = this.state;
    if (!`${columns}`) return null;
    const rowSelection = {
      selectedRowKeys,
      onChange: (sRowKeys, selectedRows) => {
        this.setState({ selectedRowKeys: sRowKeys });
        typeof this.props.onRowSelect === 'function' && this.props.onRowSelect(sRowKeys);
      },
    };
    return rowSelection;
  }
  onEdit(record, index, key, value, names, bDatas) {
    const { pageSize = 0 } = this.props;
    const { datas, current } = this.state;
    const _datas = [].concat(datas);
    _datas[pageSize * (current - 1) + index][key] = `${value}`;
    if (names) _datas[pageSize * (current - 1) + index][`${key}span`] = names;
    this.setState({ datas: _datas });
    this.onChange(_datas);
  }

  onLinkEdit(record, index, key, value, names, bDatas, linkUrl, linkKey) {
    const that = this;
    const { pageSize = 0 } = this.props;
    const { datas, current, type } = this.state;
    const _datas = [].concat(datas);
    _datas[index][key] = value;
    if (names) _datas[index][`${key}span`] = names;
    WeaTools.callApi('/api/crm/product/productInfo', 'GET', { productId: value || 0 }).then(({ datas }) => {
      _datas[index][linkKey[0]] = datas.assetunitid;
      if (names) _datas[index][`${linkKey[0]}span`] = datas.assetunitname;
      if (linkKey[1]) { _datas[index][linkKey[1]] = datas.salesprice; }

      if (type == 'addSellChance') { // 商机  新建
        _datas[index][linkKey[3]] = `${(Number(datas.salesprice) * Number(_datas[index][linkKey[2]] || 0)).toFixed(2)}`;
      }
      if (type == 'hasdiscount') { // 合同 产品
        _datas[index].sumPrice = `${(0.01 * Number(datas.salesprice) * Number(_datas[index].depreciation || 100) * Number(_datas[index].number_n || 0)).toFixed(2)}`;
      }
      that.setState({ datas: _datas });
      that.onChange(_datas);
    });
  }
  onInptEdit(record, index, key, value, names, linkKey) {
    const { pageSize = 0 } = this.props;
    const { datas, current, type } = this.state;
    const _datas = [].concat(datas);
    _datas[pageSize * (current - 1) + index][key] = value;

    if (_datas[index][linkKey[0]]) { _datas[index][linkKey[1]] = `${(Number(value) * Number(_datas[index][linkKey[0]] || 0)).toFixed(2)}`; }

    if (_datas[index][linkKey[2]]) {
      _datas[index][linkKey[1]] = `${(0.01 * Number(value) * Number(_datas[index][linkKey[0]] || 0) * Number(_datas[index][linkKey[2]] || 0)).toFixed(2)}`;
    }
    this.setState({ datas: _datas });
    this.onChange(_datas);
  }
  onSelectEdit(record, index, key, value, names, linkKey) {
    const { datas } = this.state;
    const _datas = [].concat(datas);
    const that = this;
    if (_datas[index][linkKey[0]]) {
      confirm({
        title: getLabel(25464, '付款性质已变，是否清空预算科目？'),
        content: '',
        onOk() {
          _datas[index][key] = value;
          if (_datas[index][linkKey[0]]) {
            _datas[index][linkKey[0]] = '';
            _datas[index][`${linkKey[0]}span`] = '';
          }
          that.setState({ datas: _datas });
          that.onChange(_datas);
        },
        onCancel() { },
        okText: getLabel(33703, '确定'),
        cancelText: getLabel(201, '取消'),
      });
    } else {
      _datas[index][key] = value;
      that.setState({ datas: _datas });
      that.onChange(_datas);
    }
  }
  doCopy() {
    const { datas, current, selectedRowKeys } = this.state;
    const _datas = [].concat(datas);
    selectedRowKeys.map((key) => {
      datas.map((data) => {
        if (data.key == key) {
          const _data = { ...data };
          _data.key = _datas.length;
          _datas.push(_data);
        }
      });
    });
    this.setState({ datas: _datas });
    this.onChange(_datas);
  }
  doAdd() {
    const { datas, type } = this.state;
    const _datas = [].concat(datas);
    const _data = { ...datas[0] };
    for (const k in _data) {
      _data[k] = '';
    }
    if (type == 'hasdiscount') { // 合同产品
      _data.depreciation = '100';
      _data.price = '0';
      _data.number_n = '1';
      _data.sumPrice = '0';
    }
    _data.isRemind = '0'; // 默认提醒
    if (type == 'addSellChance') { // 新建商机  产品添加
      _data.salesprice = '0';
      _data.salesnum = '1';
      _data.totelprice = '0';
    }
    _data.key = _datas.length;
    _datas.push(_data);
    this.setState({ datas: _datas });
    this.onChange(_datas);
  }
  doDelete() {
    const { datas, current, selectedRowKeys } = this.state;
    let _datas = [].concat(datas);
    selectedRowKeys.map((key) => {
      _datas = _datas.filter(data => data.key !== key);
    });
    _datas = _datas.map((data, i) => {
      const _data = { ...data };
      _data.key = i;
      return _data;
    });
    this.setState({ datas: _datas, selectedRowKeys: [] });
    this.onChange(_datas);
  }
  onChange(datas) {
    const { columns } = this.state;
    const _datas = datas.map((data, i) => {
      const _data = { ...data };
      delete _data.key;
      return _data;
    });
    typeof this.props.onChange === 'function' && this.props.onChange(_datas, columns);
  }
  showErrors() {
    let boole = true;
    toJS(this.isNoLinkInput).map((c) => { // 无链接输入框
      if (c && c.props.children.props.viewAttr == 3 && !c.props.children.props.value) {
        c.showError();
        boole = false;
      }
    });

    toJS(this.isLinkInput).map((c) => { // 有链接的输入框
      if (c && c.props.children.props.viewAttr == 3 && !c.props.children.props.value) {
        c.showError();
        boole = false;
      }
    });

    toJS(this.isNoLinkBro).map((c) => { // 无链接浏览框
      if (c && c.props.children.props.viewAttr == 3 && (!c.props || !c.props.children.props.replaceDatas[0] ||
        !c.props.children.props.replaceDatas[0].name || !c.props.children.props)) {
        c.showError();
        boole = false;
      }
    });

    toJS(this.isLinkBro).map((c) => { // 有链接的浏览框
      if (c && (!c.props || !c.props.children.props.replaceDatas[0] ||
        !c.props.children.props.replaceDatas[0].name || !c.props.children.props)) {
        c.showError();
        boole = false;
      }
    });

    toJS(this.select).map((c) => {  // 下拉框
      if (c && !c.props.children.props.value) {
        c.showError();
        boole = false;
      }
    });
    toJS(this.checkbox).map((c) => {  // 多选框
      if (c && !c.props.children.props.value) {
        c.showError();
        boole = false;
      }
    });
    toJS(this.datePicker).map((c) => {  // 日期选择
      if (c && !c.props.children.props.value) {
        c.showError();
        boole = false;
      }
    });
    return boole;
  }
}

export default WeaCrmTableEdit;
